package no.ntnu.item.ttm4120.dhcp.client;

import java.util.Random;

import no.ntnu.item.ttm4120.dhcp.AddressPool;
import no.ntnu.item.ttm4120.dhcp.AddressServerEGMI;
import no.ntnu.item.ttm4120.dhcp.AddressServerIGMI;
import no.ntnu.item.ttm4120.dhcp.data.AddressPoolEntity;

public class ClientRefreshLease  implements Runnable{

	private AddressClient addressClient = null;
	public ClientRefreshLease(AddressClient client) {
		this.addressClient = client;
	}
	
	@Override
	public synchronized void run() {
		while(true){
			
			try {
				Thread.sleep(10000);
				if (addressClient.getMap().values().size() == 0) continue;
				for (AddressPoolEntity add: addressClient.getMap().values()) {
					if((add.getLeaseTimeEnd() - System.currentTimeMillis())/2 < AddressPool.getDefaultLease()){
						// Random lease time could be used here
						((AddressServerEGMI)addressClient.getGroupProxy().getServer()).refreshLease(add.getAddress(), 20000);
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
